import { Body, Controller, Get, Param, Post, Query } from "@nestjs/common";
import { TasksService } from "./task.service";
import { Task } from "./task.entities";
import { QuantityExceededException } from "../../exception/count.limit.exception";

@Controller("tasks")
export class TasksController {
  constructor(private readonly tasksService: TasksService) {}

  /**
   * 创建任务
   * @param task
   * @param repeat
   */
  @Post("/create")
  async create(@Body() task: Task, @Query("repeat") repeat: boolean = false) {
    task.discord_session = "test";
    task.created_time = new Date();
    task.modified_time = new Date();
    task.response = "";
    task.response_state = 0;
    task.response_url = "";
    task.oss_url = "";

    try {
      const newTask = await this.tasksService.createTask(task);
      return {
        data: newTask,
        code: 200,
        message: "创建成功",
      };
    } catch (err) {
      console.log("err: ", err);
      if (err instanceof QuantityExceededException) {
        throw err;
      } else {
        return Promise.reject(err);
      }
    }
  }

  /**
   * 获取一条数据
   * @param params
   * @returns
   */
  @Get("/get/:id")
  async get(@Param() params) {
    try {
      const task = await this.tasksService.getTaskById(params.id);
      return {
        data: task,
        code: 200,
        message: "获取成功",
      };
    } catch (err) {
      return Promise.reject(err);
    }
  }

  /**
   * 获取任务课表
   * @param params
   * @returns
   */
  @Get("/page")
  async page(
    @Query("page") page: number = 1,
    @Query("pageSize") pageSize: number = 10,
    @Query("empId") empId: number
  ) {
    try {
      const result = await this.tasksService.getTasks(page, pageSize, empId);
      return {
        data: {
          page: page,
          pageSize: pageSize,
          list: result[0],
          total: result[1],
        },
        code: 200,
        message: "获取成功",
      };
    } catch (err) {
      return Promise.reject(err);
    }
  }

  /**
   * 获取当日还能使用的次数
   * @param params
   * @returns
   */
  @Get("/getCanUseCount")
  async getCanUseCount(@Query("empId") empId: number) {
    try {
      const result = await this.tasksService.getCanUseCount(empId);
      return {
        data: {
          canUseCount: result,
        },
        code: 200,
        message: "获取成功",
      };
    } catch (err) {
      return Promise.reject(err);
    }
  }

  /**
   * 重置当日还能使用的次数
   * @param params
   * @returns
   */
  @Get("/resetUseCount")
  async resetUseCount(@Query("empId") empId: number) {
    try {
      await this.tasksService.resetUseCount(empId);
      return {
        data: {
          success: true,
        },
        code: 200,
        message: "重置成功",
      };
    } catch (err) {
      return Promise.reject(err);
    }
  }
}
